//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.Mail;
using CommunityServer;
using CommunityServer.Components;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// Summary description for GalleryEmails.
	/// </summary>
	internal class GalleryEmails : Emails
	{
		private GalleryEmails()
		{
			
		}

		public static void GalleryTracking(GalleryPost post, GalleryPost parent)
		{
			if (!post.IsPicture && parent == null)
				return;

			SectionTracking(post, new EnquePostEmails(CreateGalleryPost), CreatePostFormatList(post.Gallery, post, parent) );
		}

		public static void GalleryFeedbackNotification(GalleryPost post, GalleryPost parent)
		{
			if (!post.IsPicture && parent == null)
				return;

			string postUserName = "";
			if (!Globals.IsNullorEmpty(post.Username))
				postUserName = post.Username;
			else if ( (post.User != null) && (!Globals.IsNullorEmpty(post.User.Username)) )
				postUserName = post.User.Username;
			
			if (parent.EnableAllOwnerNotification && !Globals.IsNullorEmpty(post.Gallery.Owners))
			{
				// Loop through each owner and send the notification email if that owner was 
				//	not the one who posted the feedback item.
				foreach(string username in post.Gallery.OwnerArray)
				{
					User owner = Users.FindUserByUsername(username);
					if ( !Globals.IsNullorEmpty(owner.Email) && (owner.Username != post.User.Username) )
					{
						MailMessage email = CreateGalleryFeedbackNotification(post, owner, CreatePostFormatList(post.Gallery, post, parent) );

						if(email != null && email.To != null && email.To.Trim().Length > 0)
							EmailQueueProvider.Instance().QueueEmail(email);
					}
				}
			}
			else
			{
				// Send notification email to the author of the thread if he/she was not the one who posted the feedback item.
				User owner = Users.FindUserByUsername(parent.Username);
				if ( !Globals.IsNullorEmpty(owner.Email) && (owner.Username != post.User.Username) )
				{
					MailMessage email = CreateGalleryFeedbackNotification(post, owner, CreatePostFormatList(post.Gallery, post, parent) );

					if(email != null && email.To != null && email.To.Trim().Length > 0)
						EmailQueueProvider.Instance().QueueEmail(email);
				}
			}

		}

		private static FormatList CreatePostFormatList(Gallery gallery, GalleryPost post, GalleryPost parent)
		{
		    CSContext cSContext = CSContext.Current;
		    GalleryUrls urls = GalleryUrls.Instance();
			FormatList tokens = new FormatList();
            tokens.Add("sectionName", gallery.Name);
            tokens.Add("GalleryName", gallery.Name); //Pre CS 2.1 sp1 compatability

            tokens.Add("sectionUrl", Globals.FullPath(GalleryUrls.Instance().ViewGallery(gallery.ApplicationKey)));

            tokens.Add("postedBy", post.DisplayName);
            tokens.Add("EmailName", post.DisplayName);//Pre CS 2.1 sp1 compatability

            tokens.Add("postedDate", post.UserTime.ToString("f"));
            tokens.Add("Title", post.Subject);
            tokens.Add("PictureName", post.Subject);//Pre CS 2.1 sp1 compatability
			tokens.Add("adminemailfrom", string.Format(ResourceManager.GetString("AutomatedEmail").Trim(), cSContext.SiteSettings.SiteName, cSContext.SiteSettings.AdminEmailAddress));

            tokens.Add("subscriptionLink", Globals.FullPath(urls.EmailSubscriptions(gallery.ApplicationKey)));

            if (parent != null)
            {
                tokens.Add("postLink", Globals.FullPath(urls.ViewPicture(gallery.ApplicationKey, parent)));
                tokens.Add("PictureAddress", Globals.FullPath(urls.ViewPicture(gallery.ApplicationKey, parent))); //Pre CS 2.1 sp1 compatability
                tokens.Add("titleUrl", post.TitleUrl);
                tokens.Add("originalPostName", parent.Subject);
            }
            else
            {
                tokens.Add("postLink", Globals.FullPath(urls.ViewPicture(gallery.ApplicationKey, post)));
                tokens.Add("PictureAddress", Globals.FullPath(urls.ViewPicture(gallery.ApplicationKey, post))); //Pre CS 2.1 sp1 compatability
            }

            if (post.Categories != null && post.Categories.Length > 0)
                tokens.Add("categoryname", string.Join(", ", post.Categories));//Pre CS 2.1 sp1 compatability
            else
                tokens.Add("categoryname", ResourceManager.GetString("None"));//Pre CS 2.1 sp1 compatability
		    
            tokens.Add("feedbackType", post.GalleryPostType.ToString());
            if (post.IsApproved)
                tokens.Add("publishedStatus", ResourceManager.GetString("Post_IsApproved"));
            else
                tokens.Add("publishedStatus", ResourceManager.GetString("Post_NotApproved"));

			if ((post.PostStatus & PostStatus.Spam) == PostStatus.Spam)
				tokens.Add("spamStatus", "[Spam] ");
			else if ((post.PostStatus & PostStatus.LikelySpam) == PostStatus.LikelySpam)
				tokens.Add("spamStatus", "[Possible Spam] ");
			else
				tokens.Add("spamStatus", string.Empty);

			tokens.Add("spamScore", post.SpamScore.ToString());


            tokens.Add("approve", String.Concat(Globals.FullPath(urls.ControlPanel_Photos_CommentList), "?sectionid=", gallery.SectionID, "&pid=", post.PostID));
            tokens.Add("moderate", String.Concat(Globals.FullPath(urls.ControlPanel_Photos_CommentList), "?sectionid=", gallery.SectionID, "&pid=", post.PostID));
            tokens.Add("delete", String.Concat(Globals.FullPath(urls.ControlPanel_Photos_CommentList), "?sectionid=", gallery.SectionID, "&pid=", post.PostID));
            return tokens;
		}

		private static MailMessage CreateGalleryPost(Post post, User user, FormatList formats)
		{
			string emailType = null;
			if(post.PostLevel != 0)
			{
				emailType = "GalleryComment";
			}
			else
			{
				emailType = "GalleryNewPost";
			}
			MailMessage email = GenericEmail(emailType,user,null,null,false,user.EnableHtmlEmail);

			if(email == null)
				return null;

			email.From = formats.Format(email.From);
			email.Body = formats.Format(email.Body);
			email.Subject = formats.Format(email.Subject);
			email.To = user.Email;
			
			string postbody = null;

			// if the user doesn't want HTML and the post is HTML, then strip it
			if (!user.EnableHtmlEmail && post.PostType == PostContentType.HTML) 
				postbody = Emails.FormatHtmlAsPlainText(post.RenderedBody(PostTarget.Other));
			else
				postbody =  post.RenderedBody(PostTarget.Other);
				
			postbody.Trim();

			email.Body = FormatList.Format(email.Body, "postbody", postbody);
            //email.tokens.Add(new EmailTextToken("Comment", postbody)); //Pre CS 2.1 sp1 compatability

			
			return email;
		}


		private static MailMessage CreateGalleryFeedbackNotification(Post post, User user, FormatList formats)
		{

			MailMessage email = GenericEmail("GalleryFeedbackNotification", user, null, null, false, user.EnableHtmlEmail);

			if(email == null)
				return null;

			email.From = formats.Format(email.From);
			email.Body = formats.Format(email.Body);
			email.Subject = formats.Format(email.Subject);
			email.To = user.Email;
			
			string postbody = null;

			// if the user doesn't want HTML and the post is HTML, then strip it
			if (!user.EnableHtmlEmail && post.PostType == PostContentType.HTML) 
				postbody = Emails.FormatHtmlAsPlainText(post.RenderedBody(PostTarget.Other));
			else
				postbody =  post.RenderedBody(PostTarget.Other);
				
			postbody.Trim();

			email.Body = FormatList.Format(email.Body, "postbody", postbody);
		
			return email;
		}




	}
}
